package com.bdqn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 删除DOM节点信息
 */
public class SL05 {

    public static void main(String[] args) {
        // 得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // 从DOM工厂获得DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            // 解析XML文档，得到一个Document对象，即DOM树
            Document doc = db.parse("CH02/src/删除收藏信息.xml");

            // 获得需要删除的节点
            NodeList nodeList = doc.getElementsByTagName("Brand");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element brand = (Element) nodeList.item(i);
                // 找到属性节点"SAMSUNG"
                String name = brand.getAttribute("name");
                if ("SAMSUNG".equals(name)) {
                    // 删除Brand节点（请他爹出来把它干掉）
                    brand.getParentNode().removeChild(brand);
                }
            }

            // 保存XML文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            // 设置编码方式
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            // 实例化DOMSource对象
            DOMSource source = new DOMSource(doc);
            // 实例化输出目标对象
            StreamResult result = new StreamResult(new FileOutputStream("CH02/src/删除收藏信息.xml"));
            // 将内存中的DOM保存到磁盘
            transformer.transform(source, result);

            System.out.println("删除成功！");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
